﻿using Hangfire;
using Hangfire.Dashboard.BasicAuthorization;
using Hangfire.MySql;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.BackgroundJobs.Hangfire;
using Volo.Abp.Emailing;
using Volo.Abp.Hangfire;
using Volo.Abp.Modularity;

namespace PHMEE.BackgroundJobs
{
    [DependsOn(typeof(AbpBackgroundJobsHangfireModule))]
    public class PHMEEBackgroundJobsModule : AbpModule
    {
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var configuration = context.Services.GetConfiguration();
            var hostingEnvironment = context.Services.GetHostingEnvironment();

            context.Services.AddHangfire(config =>
            {
                config.UseStorage(new MySqlStorage(configuration.GetConnectionString("Default"), new MySqlStorageOptions
                {
                    TablesPrefix = PHMEEConsts.DbTablePrefix + "hangfire"
                }));
            });

            context.Services.AddHangfireServer();
        }

        public override void OnApplicationInitialization(ApplicationInitializationContext context)
        {
            var configuration = context.GetConfiguration();
            var app = context.GetApplicationBuilder();

            app.UseAbpHangfireDashboard("/hangfire", options =>
            {
                options.DashboardTitle = "PHMEE任务调度中心";
                options.AppPath = null;
                options.Authorization = new[]
                {
                    new BasicAuthAuthorizationFilter(new BasicAuthAuthorizationFilterOptions
                    {
                        RequireSsl = false,
                        SslRedirect = false,
                        LoginCaseSensitive = true,
                        Users = new []
                        {
                            new BasicAuthAuthorizationUser
                            {
                                Login = configuration["Hangfire:Login"],
                                PasswordClear =  configuration["Hangfire:Password"]
                            }
                        }
                    })
                };
            });

            context.ServiceProvider.ConfigurePhmeeJob();

        }

    }
}
